import Vue from 'vue'
import VueRouter from 'vue-router'

import { asyncRouters } from '@/router/asyncRouters'

import local from '../util/storeManage'
import loadsh from 'lodash'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 就是通过你登录的权限是动态判断,你应该有多少路由可以跳转(就是动态引入路由,然后根据路由去遍历显示),有多少页面可以去显示(根据hidden)
const rou = loadsh.cloneDeep(asyncRouters.children)
const routes = [
  // asyncRouters,
  {
    path: '/login',
    name: 'login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/Login.vue')
  },
  // 404
  {
    path: '/404',
    component: () =>
      import(/* webpackChunkName: "error" */ '../views/Error.vue')
  },
  // 404
  {
    path: '*',
    redirect: '/404'
  }
]
// 在页面一加载的时候和 登录的时候要去判断 权限

const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (localStorage.getItem('t_k')) {
      next()
    } else {
      next('/login')
    }
  }
})

filterRouter()
export function filterRouter () {
  let role = local.get('role')
  if (!role) {
    role = 'normal'
    // return
  }
  if (asyncRouters.children) {
    // 防止asyncRouters.children 被修改,每次都需去获取完整的
    asyncRouters.children = rou
    // 一次,根据权限过滤数组
    const res = final(asyncRouters.children, role)
    // 改变可以访问的路由,只有响应的权限才能去访问
    asyncRouters.children = res
    // 合并到主路由中
    router.addRoute(asyncRouters)
    // 二次 ,跟据属性hidden去过滤,哪些路由不应该显示
    const lastMuen = fn(res)
    local.set('router', JSON.stringify(lastMuen))
  }
}
// 二次过滤,具有隐藏属性的 不会去渲染
function fn (params) {
  return params.filter(el => {
    if (el.hidden) {
      return false
    } else {
      if (el.children) {
        el.children = fn(el.children)
      }
      return true
    }
  })
}

function final (arr, role) {
  return arr.filter(el => {
    if (el.meta && el.meta.role) {
      if (el.children) {
        el.children = final(el.children, role)
      }
      return el.meta.role.includes(role)
    } else {
      return true
    }
  })
}

export default router
